import * as apis from '@/apis/modules/income.js';

const income = {
	namespaced: true,
	state: {
		incomeList: [{}],
		balance: '0.00',
		pageNum: 1,
		hasData: true,
		balanceRecords: {
			list: [{}],
			pageNum: 1,
			hasData: true,
		}
	},
	mutations: {
		save(state, {field, payload}) {
		  if (Object.prototype.toString.call(payload) === '[object Object]') {
			state[field] = { ...state[field], ...payload }
		  } else {
			state[field] = payload
		  }
		}
	},
	actions: {
		getIncomeList({ commit, state }, {agentNo, pageNum = 1} = {}) {
			apis.getIncomeList({agentNo, current: pageNum, size: 10})
				.then(({data}) => {
					let {incomeList: list} = state
					const {pages, records} = data

					if (pageNum > 1) {
						list = list.concat(records)
					} else {
						list = records || []
					}
					if (pages === pageNum) commit('save', {field: 'hasData', payload: false})

					commit('save', {field: 'incomeList', payload: list || []})
					commit('save', {field: 'pageNum', payload: pageNum})
				})
			},
			getBalance({ commit }, {agentNo}) {
				apis.getBalance(agentNo)
					.then(({data}) => {
						commit('save', {field: 'balance', payload: data.accountBalance})
					})
			},
			
			getBalanceRecords({commit, state}, {pageNum = 1} = {}) {
				apis.getBalanceRecords({current: pageNum, size: 20})
					.then(({data}) => {
						const {list} = state
						const {current, records} = data
						let newList = list
	
						if (pageNum > 1) {
							newList = newList.concat(records)
						} else {
							newList = records || []
						}
						if (current === pageNum) commit('save', {field: 'balanceRecords', payload: {hasData: false}})
	
						commit('save', {field: 'balanceRecords', payload: {list: newList || [], pageNum}})
					})
			}
	}
}

export default income